# word_definition_tab.py
from PyQt6.QtWidgets import QWidget, QVBoxLayout, QTableWidget, QTableWidgetItem, QHeaderView, QHBoxLayout, QPushButton
from PyQt6.QtCore import Qt
from db.AutoWordsDB import get_latest_word, get_next_word, get_previous_word


class WordDefinitionTab(QWidget):
    def __init__(self):
        super().__init__()
        self.init_ui()
        self.load_sample_data()

    def showEvent(self, a0):
        super().showEvent(a0)
        self.load_sample_data()

    def init_ui(self):
        # 主布局
        main_layout = QVBoxLayout()

        # 创建表格用于显示单词释义
        self.word_table = QTableWidget()
        self.word_table.setRowCount(3)  # 三行
        self.word_table.setColumnCount(1)  # 一列

        # 隐藏表头
        self.word_table.horizontalHeader().setVisible(False)
        self.word_table.verticalHeader().setVisible(False)

        # 设置表格属性
        self.word_table.setEditTriggers(QTableWidget.EditTrigger.NoEditTriggers)  # 设置为只读
        self.word_table.setSelectionMode(QTableWidget.SelectionMode.NoSelection)  # 禁止选择
        self.word_table.setShowGrid(False)  # 隐藏网格线

        # 设置列宽自动拉伸
        self.word_table.horizontalHeader().setSectionResizeMode(0, QHeaderView.ResizeMode.Stretch)

        # 设置行高
        self.word_table.setRowHeight(0, 35)
        self.word_table.setRowHeight(1, 35)
        self.word_table.setRowHeight(2, 100)

        # 启用文本换行
        self.word_table.setWordWrap(True)

        # 设置样式
        self.word_table.setStyleSheet("""
            QTableWidget {
                border: 1px solid #dcdcdc;
                border-radius: 8px;
                background-color: #ffffff;
                selection-background-color: transparent;
                gridline-color: #dcdcdc;
            }
            QTableWidget::item {
                border-bottom: 1px solid #dcdcdc;
                padding: 2px;
            }
            QTableWidget::item:last-child {
                border-bottom: none;
            }
        """)

        main_layout.addWidget(self.word_table)

        # 创建按钮布局
        button_layout = QHBoxLayout()
        button_layout.addStretch()  # 添加弹性空间，将按钮推到右侧

        # 创建按钮
        self.prev_button = QPushButton("上一个")
        self.next_button = QPushButton("下一个")

        # 连接按钮点击信号
        self.prev_button.clicked.connect(self.on_previous_clicked)
        self.next_button.clicked.connect(self.on_next_clicked)

        # 将按钮添加到布局
        button_layout.addWidget(self.prev_button)
        button_layout.addWidget(self.next_button)

        # 将按钮布局添加到主布局
        main_layout.addLayout(button_layout)

        # 设置主布局的边距
        main_layout.setContentsMargins(30, 30, 30, 30)

        self.setLayout(main_layout)
        self.load_sample_data()

    def on_next_clicked(self):
        """处理上一个按钮点击"""
        # 获取当前word_table中，word_item对应的word
        _word = self.word_table.item(0, 0).text()
        word_info = get_previous_word(_word)
        if word_info:
            word = word_info['word']
            pronunciation = word_info['pronunciation']
            meaning = word_info['meaning']
            # 设置表格内容
            self.set_word_data(word, pronunciation, meaning)

    def on_previous_clicked(self):
        """处理下一个按钮点击"""
        # 获取当前word_table中，word_item对应的word
        _word = self.word_table.item(0, 0).text()
        word_info = get_next_word(_word)
        if word_info:
            word = word_info['word']
            pronunciation = word_info['pronunciation']
            meaning = word_info['meaning']
            # 设置表格内容
            self.set_word_data(word, pronunciation, meaning)

    def load_sample_data(self):
        # 示例数据 - 展示单个单词
        word = "programming"
        pronunciation = "/ˈproʊɡræmɪŋ/"
        meaning = "编程是指创建一组指令（程序）来让计算机执行特定任务的过程。"

        word_info = get_latest_word()
        if word_info:
            word = word_info['word']
            pronunciation = word_info['pronunciation']
            meaning = word_info['meaning']
        # 设置表格内容
        self.set_word_data(word, pronunciation, meaning)

    def set_word_data(self, word, pronunciation, meaning):
        """
        设置要显示的单词数据

        Args:
            word (str): 英文单词
            pronunciation (str): 单词读音
            meaning (str): 中文描述
        """
        # 创建带样式的表格项
        word_item = QTableWidgetItem(f"{word}")
        word_item.setTextAlignment(Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignVCenter)
        word_item.setFlags(Qt.ItemFlag.ItemIsEnabled)

        pronunciation_item = QTableWidgetItem(f"{pronunciation}")
        pronunciation_item.setTextAlignment(Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignVCenter)
        pronunciation_item.setFlags(Qt.ItemFlag.ItemIsEnabled)

        meaning_item = QTableWidgetItem(f"{meaning}")
        meaning_item.setTextAlignment(Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignTop)
        meaning_item.setFlags(Qt.ItemFlag.ItemIsEnabled)

        # 设置表格项
        self.word_table.setItem(0, 0, word_item)
        self.word_table.setItem(1, 0, pronunciation_item)
        self.word_table.setItem(2, 0, meaning_item)